package com.club.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.club.common.constant.ClubTypeEnum;
import com.club.common.constant.Constant;
import com.club.common.exception.CustomException;
import com.club.entity.*;
import com.club.mapper.SysUserMapper;
import com.club.mapper.TClubMapper;
import com.club.mapper.TClubPicMapper;
import com.club.service.TClubService;
import com.club.util.RequestHelper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangfc
 * @date 2022/12/12 16:55
 */
@RequiredArgsConstructor
@Service
public class TClubServiceImpl extends ServiceImpl<TClubMapper, TClub> implements TClubService {


    private final TClubMapper tClubMapper;

    private final SysUserMapper sysUserMapper;

    private final TClubPicMapper tClubPicMapper;

    @Value("${clubImagesFilePath}")
    private String clubImagesFilePath;

    @Value("${clubAccessPath}")
    private String clubAccessPath;

    /**
     * 社团审核提交
     *
     * @param clubMap 社团的参数Map
     * @return R
     */
    public R submitClub(Map<String, Object> clubMap) {
        Integer clubId = Convert.toInt(clubMap.get("clubId"));
        if (ObjectUtil.isEmpty(clubId)) {
            //新增
            return saveTclub(clubMap);
        } else {
            //更新
            return updateTclub(clubMap, clubId);
        }
    }

    private R updateTclub(Map<String, Object> clubMap, int clubId) {
        TClub tClub = getById(clubId);
        tClub.setClubStatus(Constant.ClubStatus.AUDITING);
        tClub.setClubMessage(Convert.toStr(clubMap.get("clubMessage")));
        tClub.setClubName(Convert.toStr(clubMap.get("clubName")));
        tClub.setClubRemark(Convert.toStr(clubMap.get("clubRemark")));
        tClub.setClubType(Convert.toStr(clubMap.get("clubType")));
        tClub.setModifyTime(new Date());
        updateById(tClub);
        return R.ok("提交成功");
    }

    private R saveTclub(Map<String, Object> clubMap) {
        //当前用户id
        String id = RequestHelper.getId();
        Date nowDate = new Date();
        //生成社团编号 格式:S+年份+四位流水号
        String code = createClubNum(nowDate);

        //保存社团信息
        TClub tClub = TClub.builder()
                //编号
                .clubNumber(code)
                //创建日期
                .clubCreate(Convert.toDate(clubMap.get("createTime")))
                //社团简介
                .clubMessage(Convert.toStr(clubMap.get("clubMessage")))
                //社团类型
                .clubType(Convert.toStr(clubMap.get("clubType")))
                //社团名称
                .clubName(Convert.toStr(clubMap.get("clubName")))
                //申请说明
                .clubRemark(Convert.toStr(clubMap.get("clubRemark")))
                //创建日期
                .createTime(nowDate)
                //修改日期
                .modifyTime(nowDate)
                //当前审核状态
                .clubStatus(Constant.ClubStatus.AUDITING)
                //用户id
                .userId(Convert.toInt(id)).build();
        tClubMapper.insert(tClub);

        //保存封面
        TClubPic clubPic = TClubPic.builder()
                .clubId(tClub.getClubId())
                //图片存放路径
                .filepath(Convert.toStr(clubAccessPath + clubMap.get("imageUrl")))
                //创建时间
                .crateTime(new Date())
                //是否封面
                .isCover(Constant.YesOrNo.YES)
                .build();
        tClubPicMapper.insert(clubPic);
        return R.ok("提交成功");
    }

    /**
     * 查询所有的社团信息
     *
     * @param pageBean 分页设置
     * @return R
     */
    @Override
    public R listClub(PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<TClub> clubPage = page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), new QueryWrapper<TClub>().like(StrUtil.isNotEmpty(query), "club_name", query));
        List<TClub> clubPageRecords = clubPage.getRecords();
        List<Map<String, Object>> clubMapList = clubPageRecords.stream()
                .map(club -> {
                    //得到创建人
                    SysUser sysUser = sysUserMapper.selectById(club.getUserId());
                    //得到封面图
                    TClubPic tClubPic = tClubPicMapper.selectOne(new QueryWrapper<TClubPic>().
                            eq("club_id", club.getClubId()).eq("iscover", "1"));
                    Map<String, Object> clubMap = BeanUtil.beanToMap(club);
                    //将创建人的姓名存入返回的map中
                    clubMap.put("filepath", tClubPic.getFilepath());
                    clubMap.put("createName", sysUser.getName());
                    clubMap.put("clubCreate", DateUtil.format(club.getClubCreate(), Constant.TimePlate.STAND_TIME));
                    clubMap.put("createTime", DateUtil.format(club.getCreateTime(), Constant.TimePlate.STAND_TIME));
                    clubMap.put("modifyTime", DateUtil.format(club.getModifyTime(), Constant.TimePlate.STAND_TIME));
                    return clubMap;
                }).collect(Collectors.toList());
        Map<String, Object> responseMap = MapUtil.builder(new HashMap<String, Object>())
                .put("clubList", clubMapList)
                .put("total", clubPage.getTotal())
                .build();
        return R.ok(responseMap);
    }

    @Override
    public R auditClub(int id, int type) {
        TClub tClub = getById(id);
        String oldStatus = tClub.getClubStatus();
        //如果原状态不是审核中状态  代表已经操作过不允许再次操作
        if (!StrUtil.equals(oldStatus, Constant.ClubStatus.AUDITING)) {
            throw new CustomException("当前社团已被操作不允许再次操作");
        }
        if (Constant.ClubStatus.AUDIT_SUCCESS.equals(Convert.toStr(type))) {
            //审核状态->审核通过
            tClub.setClubStatus(Constant.ClubStatus.AUDIT_SUCCESS);
            updateById(tClub);
            return R.ok("审核通过");
        }
        //审核状态->审核不通过
        tClub.setClubStatus(Constant.ClubStatus.AUDIT_FAILURE);
        updateById(tClub);
        return R.ok("审核不通过");
    }


    @Override
    public R deleteByIds(List<Integer> ids) {
        removeByIds(ids);
        return R.ok("删除成功");
    }

    @Override
    public R listClubByUserId(int userId) {
        List<Map<String, Object>> clubMapList = tClubMapper.listClubByUserId(userId);
        return R.ok(MapUtil.builder(new HashMap<String, Object>())
                .put("clubList", clubMapList)
                .build());
    }

    @Override
    public R uploadClubImage(MultipartFile file) {
        try {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String suffixName = StrUtil.sub(fileName, StrUtil.lastIndexOf(fileName, ".", StrUtil.length(fileName), true), StrUtil.length(fileName));
                String newFileName = com.club.util.DateUtil.getCurrentDateStr() + suffixName;
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(clubImagesFilePath + newFileName));
                resultMap.put("title", newFileName);
                resultMap.put("src", clubAccessPath + newFileName);
                resultMap.put("msg", "上传成功");
            }
            return R.ok(resultMap);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @Override
    public R listClubByUser(PageBean pageBean) {
        //当前用户的id
        String userId = RequestHelper.getId();
        Page<TClub> clubPage = page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), new QueryWrapper<TClub>().eq("user_id", userId));
        //总条数
        long total = clubPage.getTotal();

        List<Map<String, Object>> clubList = clubPage.getRecords().stream()
                .map(club -> {
                    Map<String, Object> map = BeanUtil.beanToMap(club);
                    map.put("createName", RequestHelper.getUserName());
                    map.put("clubCreate", DateUtil.format(club.getClubCreate(), Constant.TimePlate.STAND_TIME));
                    map.put("createTime", DateUtil.format(club.getCreateTime(), Constant.TimePlate.STAND_TIME));
                    map.put("modifyTime", DateUtil.format(club.getModifyTime(), Constant.TimePlate.STAND_TIME));
                    return map;
                }).collect(Collectors.toList());

        Map<String, Object> responseMap = MapUtil.builder(new HashMap<String, Object>())
                .put("clubList", clubList)
                .put("total", total)
                .build();
        return R.ok(responseMap);
    }


    @Override
    public R msgByClubId(int clubId) {
        TClub tClub = getById(clubId);
        Map<String, Object> clubMap = BeanUtil.beanToMap(tClub);

        //创建人
        SysUser sysUser = sysUserMapper.selectById(tClub.getUserId());
        clubMap.put("createName", sysUser.getName());

        //找到封面图
        TClubPic clubPic = tClubPicMapper.selectOne(new QueryWrapper<TClubPic>().eq("club_id", clubId).eq("iscover", "1"));
        String filepath = clubPic.getFilepath();
        clubMap.put("imageUrl", filepath);
        clubMap.put("createTime", DateUtil.format(tClub.getCreateTime(), Constant.TimePlate.STAND_TIME));
        clubMap.put("clubCreate", DateUtil.format(tClub.getClubCreate(), Constant.TimePlate.STAND_TIME));
        clubMap.put("clubType", ClubTypeEnum.matchKey(tClub.getClubType()).getValue());
        //封装返回
        Map<String, Object> response = MapUtil.builder(new HashMap<String, Object>())
                .put("club", clubMap)
                .build();
        return R.ok(response);
    }

    /**
     * 生成社团编号
     *
     * @return 社团编号
     */
    private String createClubNum(Date nowDate) {
        //社团的总数量
        int size = tClubMapper.sizeByTClub();
        String code;
        if (size != 0) {
            String num = tClubMapper.lastNum();
            Long mathNum = Convert.toLong(num) + 1;
            //未位
            String lastNum = Convert.toStr(mathNum);
            switch (lastNum.length()) {
                case 1:
                    code = "S" + DateUtil.year(nowDate) + "000" + lastNum;
                    break;
                case 2:
                    code = "S" + DateUtil.year(nowDate) + "00" + lastNum;
                    break;
                case 3:
                    code = "S" + DateUtil.year(nowDate) + "0" + lastNum;
                    break;
                case 4:
                    code = "S" + DateUtil.year(nowDate) + lastNum;
                    break;
                default:
                    code = "S" + DateUtil.year(nowDate) + "T" + lastNum;
                    break;
            }
        } else {
            code = "S" + DateUtil.year(nowDate) + "0001";
        }
        return code;
    }
}
